package com.rongma.waterdrop.manager.bmobmanager;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.Toast;

import com.rongma.waterdrop.db.WaterDropHelper;
import com.rongma.waterdrop.exception.UserException;
import com.rongma.waterdrop.global.UploadStatus;
import com.rongma.waterdrop.global.WaterDropApplication;
import com.rongma.waterdrop.model.User;
import com.rongma.waterdrop.utils.Arith;
import com.rongma.waterdrop.utils.LogUtils;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;


/**
 * User实体类的数据库管理类
 * Created by RongMa on 16/6/5.
 */

public class UserManager
{
    private static final String DB_NAME = "user";
    private static final String COLUMN_USERNAME = "username";
    private static final String COLUMN_PORTRAIT = "imageUrl";
    private static final String COLUMN_SCORE = "score";
    private static final String COLUMN_SIGNATURE = "signature";
    private static final String COLUMN_CODETIME = "codeTime";
    private static final String COLUMN_UPLOAD = "upload";

    private static UserManager manager = new UserManager();
    private static WaterDropHelper waterDropHelper;

    private UserManager()
    {
    }

    public static UserManager getManager(Context context)
    {
        waterDropHelper = new WaterDropHelper(context);
        return manager;
    }

    //批量把数据存入数据库
    public void insertUserList(ArrayList<User> users,Context context){
        SQLiteDatabase sdb = waterDropHelper.getWritableDatabase();
        sdb.beginTransaction();
        try
        {
            ContentValues values = new ContentValues();
            for(User user : users)
            {
                values.put(COLUMN_USERNAME,user.getUsername());
                values.put(COLUMN_CODETIME,user.getCodeTime());
                values.put(COLUMN_SCORE,user.getScore());
                values.put(COLUMN_SIGNATURE,user.getSignature());
                BmobFile imageFile = user.getPortrait();
                values.put(COLUMN_PORTRAIT,imageFile.getFileUrl(context));
                values.put(COLUMN_UPLOAD,user.getUpload());
                sdb.insert(DB_NAME,null,values);
                LogUtils.show("成功添加数据"+user.getUsername());
                values.clear();
            }
            sdb.setTransactionSuccessful();
        }
        finally
        {
            sdb.endTransaction();
            sdb.close();
        }
    }

    //通过名字获取用户信息
    public User queryUserByName(String username) throws UserException {
        SQLiteDatabase sdb = waterDropHelper.getReadableDatabase();
        Cursor cursor = sdb.query(DB_NAME,null,COLUMN_USERNAME+"=?",new String[]{username},null,null,null);
        User user = new User();
        if(cursor.moveToFirst()) {
            try {
                do {
                    user.setCodeTime(cursor.getLong(cursor.getColumnIndex(COLUMN_CODETIME)));
                    user.setImageFileUrl(cursor.getString(cursor.getColumnIndex(COLUMN_PORTRAIT)));
                    user.setScore(cursor.getLong(cursor.getColumnIndex(COLUMN_SCORE)));
                    user.setSignature(cursor.getString(cursor.getColumnIndex(COLUMN_SIGNATURE)));
                    user.setUpload(cursor.getInt(cursor.getColumnIndex(COLUMN_UPLOAD)));
                }
                while (cursor.moveToNext());
            } finally {
                cursor.close();
                sdb.close();
            }
        }
        return user;
    }

    //获取所有的用户资料
    public ArrayList<User> queryAllUsers(){
        SQLiteDatabase sdb = waterDropHelper.getReadableDatabase();
        Cursor cursor = sdb.query(DB_NAME,null,null,null,null,null,"score DESC");
        ArrayList<User> users = new ArrayList<User>();
        if(cursor.moveToFirst()) {
            try {
                do {
                    User user = new User();
                    user.setImageFileUrl(cursor.getString(cursor.getColumnIndex(COLUMN_PORTRAIT)));
                    user.setScore(cursor.getLong(cursor.getColumnIndex(COLUMN_SCORE)));
                    user.setUsername(cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)));
                    user.setUpload(cursor.getInt(cursor.getColumnIndex(COLUMN_UPLOAD)));
                    users.add(user);
                }
                while (cursor.moveToNext());
            } finally {
                cursor.close();
                sdb.close();
            }
        }
        return users;
    }


    private void updateUploadStatus(String username,int upload)
    {
        SQLiteDatabase sdb = waterDropHelper.getWritableDatabase();
        sdb.beginTransaction();
        try
        {
            ContentValues values = new ContentValues();
            values.put(COLUMN_UPLOAD,upload);
            sdb.update(DB_NAME,values,COLUMN_USERNAME + "=?",new String[]{username});
            sdb.setTransactionSuccessful();
        }
        finally
        {
            sdb.endTransaction();
            sdb.close();
        }
    }

    //修改用户的编程时间
    public void updateUserCodeTime(String username,int codetime,Context context)
    {
        SQLiteDatabase sdb = waterDropHelper.getWritableDatabase();
        sdb.beginTransaction();
        long userCodeTime = queryUserCodeTime(username);
        try
        {
            ContentValues values = new ContentValues();
            values.put(COLUMN_CODETIME, Arith.add(userCodeTime,codetime));
            sdb.update(DB_NAME,values,COLUMN_USERNAME + "=?",new String[]{username});
            sdb.setTransactionSuccessful();
            //上传数据到Bmob后台
            uploadUserToBmob(username,context);
        }
        finally
        {
            sdb.endTransaction();
            sdb.close();
        }
    }

    /*
    * 上传数据到Bmob数据库
    * 如果上传失败,则修改upload值
    * */
    private void uploadUserToBmob(final String username,final Context context) {
        BmobQuery<User> bmobQuery = new BmobQuery<User>();
        bmobQuery.addWhereEqualTo("username",username);
        bmobQuery.findObjects(context, new FindListener<User>() {
            @Override
            public void onSuccess(List<User> list) {
                User user = list.get(0);
                if(user != null) {
                    String objId = user.getObjectId();
                    try {
                        user = queryUserByName(username);
                        user.update(context, objId, new UpdateListener() {
                            @Override
                            public void onSuccess() {
                                LogUtils.show("User "+username+"的codeTime数据更新成功------!!");
                                //设置upload值为NONE
                                updateUploadStatus(username,UploadStatus.NONE);

                            }

                            @Override
                            public void onFailure(int i, String s) {
                                Toast.makeText(context,"数据上传失败,请检查网络连接并重试",Toast.LENGTH_SHORT).show();
                                LogUtils.show("User "+username+"的codeTime数据更新失败,原因:"+s);
                                //设置upload值为UPDATE
                                updateUploadStatus(username,UploadStatus.UPDATE);

                            }
                        });
                    } catch (UserException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(int i, String s) {

            }
        });
    }

    //获取用户的编程时间
    public int queryUserCodeTime(String username)
    {
        SQLiteDatabase sdb = waterDropHelper.getReadableDatabase();
        Cursor cursor = sdb.query(DB_NAME,new String[]{COLUMN_CODETIME},COLUMN_USERNAME+"=?",new String[]{username},null,null,null);
        try
        {
            if (cursor.moveToFirst())
            {
                return cursor.getInt(cursor.getColumnIndex(COLUMN_CODETIME));
            }
        }
        finally
        {
            cursor.close();
        }
        return 0;
    }

    //上传所有需要修改的User数据
    public void updateUsersToBmob(Context context)
    {
        SQLiteDatabase sdb = waterDropHelper.getReadableDatabase();
        Cursor cursor = sdb.query(DB_NAME,new String[]{COLUMN_USERNAME},COLUMN_UPLOAD+"=?",new String[]{UploadStatus.UPDATE+""},null,null,null);
        if(cursor.moveToFirst())
        {
            try
            {
                do
                {
                    uploadUserToBmob(cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)),context);
                } while(cursor.moveToNext());
            }
            finally
            {
                cursor.close();
                sdb.close();
            }
        }
    }

    //修改NPC的分数
    public void changeNPCScore(Context context)
    {
        ArrayList<User> users = queryAllUsers();
        for(User user : users)
        {
            if("戎码".equals(user.getUsername()))
            {
                continue;
            }
            //修改分数
            long score = (long) Arith.add(user.getScore(),Math.random()*1000);
            Log.e("rongma",user.getUsername()+"--->"+score);
            updateUserScore(user.getUsername(),score,context);
        }
    }

    //修改用户的编程时间
    public void updateUserScore(String username,long score,Context context)
    {
        SQLiteDatabase sdb = waterDropHelper.getWritableDatabase();
        sdb.beginTransaction();
        try
        {
            ContentValues values = new ContentValues();
            values.put(COLUMN_SCORE, score);
            sdb.update(DB_NAME,values,COLUMN_USERNAME + "=?",new String[]{username});
            sdb.setTransactionSuccessful();
            //上传数据到Bmob后台
            uploadUserToBmob(username,context);
        }
        finally
        {
            sdb.endTransaction();
            sdb.close();
        }
    }
}
